﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Xml;
using Tracy.Agent.DownloaderAdapter;
using Tracy.CoreLib.Data;
using Tracy.CoreLib;
using Tracy.Engine;
using System.IO;
using System.Collections.Specialized;
using System.Reflection;
using CoreLib.Message;


namespace Tracy
{
    public partial class FormMain : AbstractMessageHandlerForm
    {
        private bool loadSuccessful = false;
        private const int LISTVIEWTASK_COLUMN_TITLE = 0;
        private const int LISTVIEWTASK_COLUMN_LINK = 1;
        private const int LISTVIEWTASK_COLUMN_FOLDER = 2;
        private const int LISTVIEWTASK_COLUMN_LASTUPDATED = 3;
        private const int LISTVIEWTASK_COLUMN_STATUS = 4;
        private const int LISTVIEWTASK_COLUMN_ID = 5;

        private TracyEngine tracyEngine;

        /// <summary>
        /// 初始化UI
        /// </summary>
        private void LoadUIData()
        {
            foreach (RssFeedSource source in tracyEngine.GetRssSources())
            {
                listBoxFeedSource.Items.Add(source);
            }
            foreach (RssFilter filter in tracyEngine.GetRssFilters())
            {
                listBoxFilter.Items.Add(filter);
            }
            foreach (ResourceItem item in tracyEngine.GetCurrentResources())
            {
                AddResourceToListView(item);
            }
            listBoxFeedSource.Enabled = true;
            listBoxFilter.Enabled = true;
            listViewTasks.Enabled = true;
            toolStripButtonDownload.Enabled = true;
            toolStripButtonUpdateFeed.Enabled = true;
            loadSuccessful = true;
        }

        public FormMain()
        {
            InitializeComponent();
            tracyEngine = new TracyEngine();
            tracyEngine.OnMessageProcessed += new EventHandler<TracyMessageEventArgs>(tracyEngine_OnMessageProcessed);
            tracyEngine.OnQueueModified += new EventHandler<TracyGeneralEventArgs>(tracyEngine_OnQueueModified);
            tracyEngine.MessageGenerator.InitEngine(this);
            listViewTasks.ListViewItemSorter = new ListViewColumnSorter();
            listViewTasks.ColumnClick += new ColumnClickEventHandler(ListViewHelper.ListView_ColumnClick);
        }

        /// <summary>
        /// 退出
        /// </summary>
        private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if(loadSuccessful) tracyEngine.SaveSettings();
            tracyEngine.ShutDown();
        }

        /// <summary>
        /// 消息队列发生了更改
        /// </summary>
        void tracyEngine_OnQueueModified(object sender, TracyGeneralEventArgs e)
        {
            if (this.IsDisposed) return;
            if (this.InvokeRequired)
            {
                UpdateUICallbackGeneral d = new UpdateUICallbackGeneral(tracyEngine_OnQueueModified);
                this.Invoke(d, new object[] { sender, e });
            }
            else
            {
                int queueItemCount = Convert.ToInt32(e.Data);
                if (queueItemCount == 0) SetUIIdle();
                else SetUIBusy();
            }
        }

        #region ListView操作
        /// <summary>
        /// 获得lvitem的状态
        /// </summary>
        /// <param name="lvitem"></param>
        /// <returns></returns>
        private string GetTaskStatus(ListViewItem lvitem)
        {
            return lvitem.SubItems[LISTVIEWTASK_COLUMN_STATUS].Text;
        }

        /// <summary>
        /// 设置lvitem及其对应资源的状态
        /// </summary>
        private void SetTaskStatus(ListViewItem lvitem, string status)
        {
            //lvitem.SubItems[LISTVIEWTASK_COLUMN_STATUS].Text = status;
            //if (!onlyUpdateUI)
            //{
                tracyEngine.MessageGenerator.UpdateStatusById(this, GetTaskId(lvitem), status);
            //}
        }

        /// <summary>
        /// 获得lvitem的ID
        /// </summary>
        /// <param name="lvitem"></param>
        /// <returns></returns>
        private int GetTaskId(ListViewItem lvitem)
        {
            return Convert.ToInt32(lvitem.SubItems[LISTVIEWTASK_COLUMN_ID].Text);
        }

        /// <summary>
        /// 将资源显示到ListView中
        /// </summary>
        private void AddResourceToListView(ResourceItem item)
        {
            ListViewItem lvitem = new ListViewItem(item.Title);
            lvitem.Name = item.Id.ToString();//设置Key
            lvitem.SubItems.Add(new ListViewItem.ListViewSubItem(lvitem, item.Link));
            lvitem.SubItems.Add(new ListViewItem.ListViewSubItem(lvitem, item.Folder));
            lvitem.SubItems.Add(new ListViewItem.ListViewSubItem(lvitem, item.LastUpdate.ToString()));
            lvitem.SubItems.Add(new ListViewItem.ListViewSubItem(lvitem, item.Status));
            lvitem.SubItems.Add(new ListViewItem.ListViewSubItem(lvitem, item.Id.ToString()));
            listViewTasks.Items.Insert(0, lvitem);
        }
        #endregion

        #region 源列表逻辑
        /// <summary>
        /// 源列表右键菜单事件
        /// </summary>
        private void contextMenuStripSourceManagement_Opening(object sender, CancelEventArgs e)
        {
            if (listBoxFeedSource.SelectedIndex != -1)
            {
                removeSourceToolStripMenuItem.Enabled = true;
                modifySourceToolStripMenuItem.Enabled = true;
                addFilterFromSourceToolStripMenuItem.Enabled = true;
            }
            else
            {
                removeSourceToolStripMenuItem.Enabled = false;
                modifySourceToolStripMenuItem.Enabled = false;
                addFilterFromSourceToolStripMenuItem.Enabled = false;
            }
        }

        /// <summary>
        /// 添加源
        /// </summary>
        private void addSourceToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormFeedSource formNewFeed = new FormFeedSource(tracyEngine);
            formNewFeed.ShowDialog();
            if (formNewFeed.DialogResult == DialogResult.OK && formNewFeed.Changed)
            {
                if (tracyEngine.GetRssSources().Contains(formNewFeed.NewSource.Key))
                {
                    MessageBox.Show("Rss源已存在");
                    return;
                }
                tracyEngine.MessageGenerator.AddItem(this, formNewFeed.NewSource);
                if (MessageBox.Show("是否创建默认过滤器（下载所有该Rss源的资源）？", "创建过滤器", MessageBoxButtons.OKCancel) == DialogResult.OK)
                { 
                    CreateFilterFromSource(formNewFeed.NewSource); 
                }
            }
        }

        private void CreateFilterFromSource(RssFeedSource source)
        {
            
            RssFilter defaultFilter = new RssFilter();
            defaultFilter.Title = source.Title;
            defaultFilter.Description = source.Title + "的默认过滤器";
            defaultFilter.Filter = new Filter();
            defaultFilter.Filter.FilterExpr = ".*";

            FormFilter formNewFilter = new FormFilter(tracyEngine, defaultFilter);
            formNewFilter.SetDefaultSource(source);

            formNewFilter.ShowDialog();
            if (formNewFilter.DialogResult == DialogResult.OK && formNewFilter.Changed)
            {
                ProcessAddFilterResult(formNewFilter);
            }
            
        }

        /// <summary>
        /// 修改源
        /// </summary>
        private void modifySourceToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormFeedSource formNewFeed = new FormFeedSource((RssFeedSource)listBoxFeedSource.SelectedItem, tracyEngine);
            formNewFeed.ShowDialog();
            if (formNewFeed.DialogResult == DialogResult.OK && formNewFeed.Changed)
            {
                RssFeedSource oldItem = (RssFeedSource)listBoxFeedSource.SelectedItem;
                
                tracyEngine.MessageGenerator.ReplaceItem(this, formNewFeed.NewSource,oldItem);
                
            }
        }

        /// <summary>
        /// 删除源
        /// </summary>
        private void removeSourceToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tracyEngine.MessageGenerator.RemoveItem(this, (IManagedXmlModelItem)listBoxFeedSource.SelectedItem);
            listBoxFeedSource.Items.Remove(listBoxFeedSource.SelectedItem);
        }

        /// <summary>
        /// 为源添加过滤器
        /// </summary>
        private void addFilterFromSourceToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (RssFeedSource source in listBoxFeedSource.SelectedItems)
            {
                CreateFilterFromSource(source);
            }
        }
        #endregion

        #region 过滤器列表逻辑
        /// <summary>
        /// 过滤器列表右键菜单
        /// </summary>
        private void contextMenuStripFilterManagement_Opening(object sender, CancelEventArgs e)
        {
            if (listBoxFilter.SelectedIndex != -1)
            {
                removeFilterToolStripMenuItem.Enabled = true;
                modifyFilterToolStripMenuItem.Enabled = true;
            }
            else
            {
                removeFilterToolStripMenuItem.Enabled = false;
                modifyFilterToolStripMenuItem.Enabled = false;
            }
        }

        /// <summary>
        /// 添加过滤器
        /// </summary>
        private void addFilterToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormFilter formNewFilter = new FormFilter(tracyEngine);
            formNewFilter.ShowDialog();
            if (formNewFilter.DialogResult == DialogResult.OK && formNewFilter.Changed)
            {
                ProcessAddFilterResult(formNewFilter);
            }
        }

        private void ProcessAddFilterResult(FormFilter formNewFilter)
        {
            tracyEngine.MessageGenerator.AddItem(this, formNewFilter.NewFilter);

            //添加Tag
            TracyProperty filterSourceProperty = tracyEngine.Bus.TracyTagManager.GetPropertyByName(Constants.CONST_PROPERTY_FILTERSOURCE);
            if (filterSourceProperty != null)
            {
                foreach (RssFeedSource feedSource in formNewFilter.SourcesToAdd)
                    tracyEngine.MessageGenerator.AssignTag(this, filterSourceProperty, formNewFilter.NewFilter, feedSource);

            }
        }

        /// <summary>
        /// 修改过滤器
        /// </summary>
        private void modifyFilterToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormFilter formNewFilter = new FormFilter(tracyEngine, (RssFilter)listBoxFilter.SelectedItem);
            formNewFilter.ShowDialog();
            if (formNewFilter.DialogResult == DialogResult.OK && formNewFilter.Changed)
            {
                RssFilter oldItem = (RssFilter)listBoxFilter.SelectedItem;
                
                tracyEngine.MessageGenerator.ReplaceItem(this, formNewFilter.NewFilter, oldItem);
                
                //添加/删除Tag
                TracyProperty filterSourceProperty = tracyEngine.Bus.TracyTagManager.GetPropertyByName(Constants.CONST_PROPERTY_FILTERSOURCE);
                if (filterSourceProperty != null)
                {
                    foreach (RssFeedSource feedSource in formNewFilter.SourcesToAdd)
                        tracyEngine.MessageGenerator.AssignTag(this, filterSourceProperty, formNewFilter.NewFilter, feedSource);

                    foreach (RssFeedSource feedSource in formNewFilter.SourcesToRemove)
                        tracyEngine.MessageGenerator.RemoveTag(this, formNewFilter.NewFilter, feedSource); 
                }
                
                
            }
        }

        /// <summary>
        /// 删除过滤器
        /// </summary>
        private void removeFilterToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tracyEngine.MessageGenerator.RemoveItem(this, (IManagedXmlModelItem)listBoxFilter.SelectedItem);
            listBoxFilter.Items.Remove(listBoxFilter.SelectedItem);
        }

        private void listViewTasks_ColumnClick(object sender, ColumnClickEventArgs e)
        {

        }
        #endregion

        #region 任务列表逻辑
        /// <summary>
        /// 任务列表右键菜单事件
        /// </summary>
        private void contextMenuStripTaskList_Opening(object sender, CancelEventArgs e)
        {
            if (listViewTasks.SelectedItems.Count == 0) e.Cancel = true;
        }

        /// <summary>
        /// 打开所在文件夹
        /// </summary>
        private void openContainingFolderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StringCollection openedFolders = new StringCollection();
            string tmpFolder = "";
            foreach (ListViewItem lvitem in listViewTasks.SelectedItems){
                tmpFolder=lvitem.SubItems[LISTVIEWTASK_COLUMN_FOLDER].Text;
                if (!openedFolders.Contains(tmpFolder))
                {
                    System.Diagnostics.Process.Start(Constants.CONST_APPLICATION_PATH_EXPLORER, tmpFolder);
                    openedFolders.Add(tmpFolder);
                }
            }
        }

        /// <summary>
        /// 将状态设为New
        /// </summary>
        private void statusNewToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem lvitem in listViewTasks.SelectedItems)
            {
                SetTaskStatus(lvitem, Constants.CONST_RESOURCE_STATUS_NEW);
            }
        }

        /// <summary>
        /// 将状态设为SentToDownload
        /// </summary>
        private void statusSentToDownloadToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem lvitem in listViewTasks.SelectedItems)
            {
                SetTaskStatus(lvitem, Constants.CONST_RESOURCE_STATUS_SENTTODOWNLOAD);
            }
        }

        /// <summary>
        /// 将状态设为Completed
        /// </summary>
        private void statusCompletedToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem lvitem in listViewTasks.SelectedItems)
            {
                SetTaskStatus(lvitem, Constants.CONST_RESOURCE_STATUS_COMPLETED);
            }
        }
        #endregion


        /// <summary>
        /// 更新源
        /// </summary>
        private void toolStripButtonUpdateFeed_Click(object sender, EventArgs e)
        {
            toolStripButtonUpdateFeed.Enabled = false;
            tracyEngine.MessageGenerator.UpdateFeed(this);
        }

        /// <summary>
        /// 下载状态为New的资源
        /// </summary>
        private void toolStripButtonDownload_Click(object sender, EventArgs e)
        {
            toolStripButtonDownload.Enabled = false;
            foreach (ListViewItem lvitem in listViewTasks.Items)
            {
                if (GetTaskStatus(lvitem) == Constants.CONST_RESOURCE_STATUS_NEW)
                {
                    tracyEngine.MessageGenerator.SendToDownload(this, Convert.ToInt32(lvitem.SubItems[LISTVIEWTASK_COLUMN_ID].Text));
                    //SetTaskStatus(lvitem, Constants.CONST_RESOURCE_STATUS_SENTTODOWNLOAD, true);
                }
            }
        }

        #region UI用户体验优化
        private void SetUIIdle()
        {
            labelStatus.Text = Constants.CONST_MOE_MESSAGE_STATUS_READY;
        }

        private void SetUIBusy()
        {
            labelStatus.Text = Constants.CONST_MOE_MESSAGE_STATUS_BUSY;
        }
        #endregion


    }
}
